﻿using System;
using System.Data;
using System.Collections.Generic;
using IDAL;
using Model;
using Model.RF.Package;
using BLL.RF.Package;
using System.Configuration;

namespace BLL
{
    public class PackageProduct
    {
        private static readonly string Test_to_Package = ConfigurationManager.AppSettings["Test_to_Package"];

        private static readonly IPackageProduct dal = DALFactory.DataAccess.CreatePackageProduct();

        public TestInfo GetlastTest(string productSN)
        {
            if (string.IsNullOrEmpty(productSN))
                return null;
            return dal.GetlastTest(productSN);
        }

        /// <summary>
        /// 关联前判断交调是否通过
        /// </summary>
        /// <param name="productSN"></param>
        /// <returns></returns>
        public PIMTestInfo GetlastPIMTest(string productSN)
        {
            return dal.GetlastPIMTest(productSN);
        }

        public void Insert(PackageProductInfo ppi)
        {
            dal.Insert(ppi);
        }

        public void Update(PackageProductInfo ppi)
        {
            dal.Update(ppi);
        }

        /// <summary>
        /// 成品包装做记录
        /// </summary>
        /// <param name="packageProductSN"></param>
        /// <param name="packer"></param>
        /// <param name="packageTime"></param>
        public void SetPackaged(string packageProductSN, string packer, DateTime packageTime)
        {
            dal.SetPackaged(packageProductSN, packer, packageTime);
        }

        public PackageProductInfo GetPackageProductbyPackageProductSN(string packageProductSN)
        {
            return dal.GetPackageProductbyPackageProductSN(packageProductSN);
        }

        public PackageProductInfo GetPackageProductbyProductSN(string productSN)
        {
            if (string.IsNullOrEmpty(productSN))
                return null;
            return dal.GetPackageProductbyProductSN(productSN);
        }

        public PackageProductInfo GetAllPackagebyProductSN(string productSN)
        {
            return dal.GetAllPackagebyProductSN(productSN);
        }

        public IList<PackageProductInfo> GetPackageTestsbyPIDDT(string productTypeID, DateTime starttime, DateTime stoptime)
        {
            return dal.GetPackageTestsbyPIDDT(productTypeID, starttime, stoptime);
        }

        public IList<PackageProductInfo> GetPackageTestsbyUIDDT(string userID, DateTime starttime, DateTime stoptime)
        {
            return dal.GetPackageTestsbyUIDDT(userID, starttime, stoptime);
        }

        public IList<PackageProductInfo> GetPackagedProductsbyPIDDT(string productTypeID, DateTime starttime, DateTime stoptime)
        {
            return dal.GetPackagedProductsbyPIDDT(productTypeID, starttime, stoptime);
        }

        public IList<PackageProductInfo> GetPackagedProductsbyUIDDT(string userID, DateTime starttime, DateTime stoptime)
        {
            return dal.GetPackagedProductsbyUIDDT(userID, starttime, stoptime);
        }

        public IList<PackageProductInfo> GetPackagedProductsbyPIDDT_forPrinter(string productTypeID, int quantity)
        {
            return dal.GetPackagedProductsbyPIDDT_forPrinter(productTypeID, quantity);
        }

        public IList<PackageProductInfo> GetPackageTestsbyDT(DateTime starttime, DateTime stoptime)
        {
            return dal.GetPackageTestsbyDT(starttime, stoptime);
        }

        public IList<PackageProductInfo> GetPackagedProductsbyDT(DateTime starttime, DateTime stoptime)
        {
            return dal.GetPackagedProductsbyDT(starttime, stoptime);
        }

        public int GetQbyCurrentDay()
        {
            return dal.GetQbyCurrentDay();
        }

        public string IsUnionProductSN(string productSN)
        {
            if (string.IsNullOrEmpty(productSN))
                return null;
            return dal.IsUnionProductSN(productSN);
        }

        /// <summary>
        /// 判断序列号是不是满足腔体序列号编码格式：供应商代码+319/3JS etc。
        /// </summary>
        /// <param name="productSN">序列号（不区分腔体或成品的）</param>
        /// <returns>符合则为true</returns>
        public bool IsFormated_ProductSN(string productSN)
        {
            return string.Equals(productSN, dal.IsUnionProductSN(productSN), StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// 判断是不是关联过（有关联数据）的成品序列号
        /// </summary>
        /// <param name="packageProductSN"></param>
        /// <returns>序列号作为成品序列号，且有关联数据则返回true</returns>
        public bool HasUnionData_PackageProductSN(string packageProductSN)
        {
            return !string.IsNullOrEmpty(dal.GetPackageProductbyPackageProductSN(packageProductSN).PackageProductSN);
        }

        /// <summary>
        /// 1.关联时，判断参数中的PID，是不是与SN之前工序使用的PID一致
        /// 2.此工序只判断已有数据的情况，没数据的话不影响(中兴产品上线即关联，所以除外)
        /// </summary>
        /// <param name="productSN"></param>
        /// <param name="productTypeID"></param>
        /// <returns>中兴产品，或一致时，返回true</returns>
        public bool IsValidPID_forUnion(string productSN, string productTypeID)
        {
            //ProductType p=new ProductType();
            //if (p.LoadEntity(productTypeID).CustomerName.Equals("中兴(ZTE)", StringComparison.OrdinalIgnoreCase))
            //    return true;
            //else
            return dal.IsvalidPID(productSN, productTypeID);
        }

        public string Isvalid3bk(string productTypeID, string sN3BK)
        {
            if (string.IsNullOrEmpty(productTypeID))
                return null;
            return dal.Isvalid3bk(productTypeID, sN3BK);
        }

        public bool IsvalidPID(string productSN, string productTypeID)
        {
            return dal.IsvalidPID(productSN, productTypeID);
        }

        public string IsvalidMatchingSN(string packageProductSN, string productTypeID)
        {
            return dal.IsvalidMatchingSN(packageProductSN, productTypeID);
        }

        public string IsvalidMatchingSN_SN3BK(string packageProductSN)
        {
            if (string.IsNullOrEmpty(packageProductSN))
                return null;
            return dal.IsvalidMatchingSN_SN3BK(packageProductSN);
        }

        public string GetProductTypeID(string productSN)
        {
            if (string.IsNullOrEmpty(productSN))
                return null;
            return dal.GetProductTypeID(productSN);
        }

        public IList<Time_QInfo> GetPackagedQbyAllPIDDT(DateTime starttime, DateTime stoptime)
        {
            return dal.GetPackagedQbyAllPIDDT(starttime, stoptime);
        }



        //重构代码---------------------------------------------------------------------------------------------------
        public int CheckandPackage(string var_productSN, string var_tag, string var_outSN3BK, string var_2DSN, string packer, out string str)
        {
            Repair rep = new Repair();
            PackageProductInfo ppi = dal.GetPackageProductbyPackageProductSN(var_productSN);
            ProductType pt = new ProductType();
            if (string.IsNullOrEmpty(ppi.PackageProductSN))
            {
                str = "没有关联过的成品序列号！请先完成关联流程";
                return 0;
            }
            else
            {
                RepairInfo repInfo = rep.GetRepairbyLast(ppi.ProductSN);
                //返修之后，可以再包装
                if (ppi.IsPackage == "Yes" &&
                    dal.GetAllPackagebyProductSN(ppi.ProductSN).PackageTime > (string.IsNullOrEmpty(repInfo.ProductSN) ? DateTime.Now.AddYears(-10) : repInfo.RecordTime))
                {
                    str = "已经包装过的产品，无法重复包装！";
                    return 0;
                }
                else
                {
                    ProductTypeInfo pti = pt.LoadEntity(dal.GetPackageProductbyPackageProductSN(var_productSN).ProductTypeID);
                    switch (pti.CustomerName)
                    {
                        case "中兴(ZTE)":
                            if (!var_productSN.Equals(var_tag, StringComparison.OrdinalIgnoreCase))
                            {
                                str = "此中兴产品外箱标签与成品序列号不一致，请检查确认！";
                                return 0;
                            }
                            break;
                        case "阿朗(Alcatel-Lucent)":
                            if (!var_productSN.Equals(var_tag, StringComparison.OrdinalIgnoreCase))
                            {
                                str = "此阿朗产品外箱标签与成品序列号不一致，请检查确认！";
                                return 0;
                            }
                            else
                            {
                                if (!var_outSN3BK.Equals(pti.SN3BK, StringComparison.OrdinalIgnoreCase))
                                {
                                    str = "此阿朗产品外箱成品序列号编码不正确，请检查确认！";
                                    return 0;
                                }
                                break;
                            }
                        case "诺西(NSN)":
                            //if (!var_tag.Equals("S" + var_productSN, StringComparison.OrdinalIgnoreCase))
                            if (!var_productSN.Equals(var_tag, StringComparison.OrdinalIgnoreCase))
                            {
                                str = "此诺西产品外箱序列号标签编码不正确，请检查确认！";
                                return 0;
                            }
                            else
                            {
                                //if (!var_outSN3BK.Equals("1P" + pti.SN3BK, StringComparison.OrdinalIgnoreCase))
                                if (!var_outSN3BK.Equals(pti.SN3BK, StringComparison.OrdinalIgnoreCase))
                                {
                                    str = "此诺西产品外箱成品序列号编码不正确，请检查确认！";
                                    return 0;
                                }
                                else
                                {
                                    if (!(var_2DSN.Contains(var_tag) && var_2DSN.Contains(var_outSN3BK)))
                                    {
                                        str = "此诺西产品2D条码没有全部包含外箱序列号标签和外箱成品序列号，请检查确认！";
                                        return 0;
                                    }
                                    break;//还有2D标签没有判断
                                }
                            }
                        default:
                            if (!var_productSN.Equals(var_tag, StringComparison.OrdinalIgnoreCase))
                            {
                                str = "此产品外箱标签与成品序列号不一致，请检查确认！";
                                return 0;
                            }
                            break;
                        //str = "此腔体的客户超出范围，请联系相关人员！";
                        //return 0;
                    }
                    //加入装箱前九大关键工序检查与高频、气密返修相关工序复测判断逻辑 
                    //if (!dal.IsValid_NineStep_DataCheck(ppi.ProductSN,out str))
                    //{
                    //    return 0;
                    //}                    
                    if (!Package_HasValidSevenStep(ppi.ProductSN, ppi.ProductTypeID))
                    {
                        str = "不能包装，请反查此腔体的七大管控工序的数据!";
                        return 0;
                    }
                    if (!Package_HasValidRFSourceStep(ppi.ProductSN, ppi.ProductTypeID))
                    {
                        str = "不能包装，请反查此腔体的有源管控工序的数据！";
                        return 0;
                    }
                    if (bool.Parse(Test_to_Package))
                    {
                        RepairItem repi = new RepairItem();
                        RepairItemInfo repiInfo = repi.GetRepairItembyLastSNStep(var_productSN, "电性能测试");
                        TestInfo ti = dal.GetlastTest(dal.IsUnionProductSN(var_productSN));
                        //返修之后的判断，忽略返修记录时间之前的数据
                        if (ti.IsPass == "Pass" && ti.TestTime > (string.IsNullOrEmpty(repiInfo.ProductSN) ? DateTime.Now.AddYears(-10) : repiInfo.RecordTime))
                        {
                            if (!ppi.ProductTypeID.Equals(ti.ProductTypeID, StringComparison.OrdinalIgnoreCase))   //包装时,比较关联时录入的S代码和最后一次合格的电性能测试时用的配置文件的S代码
                            {
                                str = "关联所用产品类型与电性能测试所用产品类型不一致！";
                                return 0;
                            }
                            else
                            {
                                DateTime dt = DateTime.Now;
                                dal.SetPackaged(var_productSN, packer, dt);
                                str = "包装成功！";
                                return 1;
                            }
                        }
                        else if (ti.IsPass == "Fail" && ti.TestTime > (string.IsNullOrEmpty(repiInfo.ProductSN) ? DateTime.Now.AddYears(-10) : repiInfo.RecordTime))
                        {
                            str = "产品测试未通过！";
                            return 2;
                        }
                        else
                        {
                            str = "没有相关的测试记录！";
                            return 0;
                        }
                    }
                    else
                    {
                        DateTime dt = DateTime.Now;
                        dal.SetPackaged(var_productSN, packer, dt);
                        str = "包装成功！";
                        return 1;
                    }
                }
            }
        }

        public bool ProductSNUnion(List<string> var_productSN_list, string var_packagePrdouctSN, string var_SN3BK, string var_productTypeName, string userID, out string str)
        {
            foreach (string sn in var_productSN_list)
            {
                if (!IsFormated_ProductSN(sn))             //腔体编码规则的判断，之前是去掉的，中兴产品成品序列号上线后加上            
                {
                    str = "腔体序列号" + sn + "不符合编码规则，请检查！";
                    return false;
                }
                if (!IsvalidProductSNtoUnion(sn, out str))
                {
                    return false;
                }
            }
            if (!IsvalidPackageProductSNtoUnion(var_packagePrdouctSN, out str))
            {
                return false;
            }
            else
            {
                if (!IsvalidProductTypeNametoUnion(var_productTypeName, out str))
                {
                    return false;
                }
                else
                {
                    ProductType pt = new ProductType();
                    ProductTypeInfo pti = pt.GetProductTypebyName(var_productTypeName);
                    foreach (string sn in var_productSN_list)
                    {
                        if (!this.IsValidPID_forUnion(sn, pti.ProductTypeID))
                        {
                            str = "产品类型与腔体序列号" + sn + "对应不正确，或前道工序数据不合格，请反查前道工序数据！";
                            return false;
                        }
                    }
                    if (dal.Isvalid3bk(var_productTypeName, var_SN3BK) != "1")
                    {
                        str = "产品的客户成品条码不正确，请检查对应关系";
                        return false;
                    }
                    else
                    {
                        if (dal.IsvalidMatchingSN(var_packagePrdouctSN, var_productTypeName) != "1")
                        {
                            str = "产品的成品序列号格式不正确，请检查对应关系";
                            return false;
                        }
                        else
                        {
                            DateTime dt = DateTime.Now;
                            switch (var_productSN_list.Count)
                            {
                                case 2:
                                    foreach (string sn in var_productSN_list)
                                    {
                                        SNUnion union = new SNUnion();
                                        SNUnionInfo sui = new SNUnionInfo()
                                        {
                                            PackageProductSN = var_packagePrdouctSN,
                                            ProductSN = sn,
                                            ProductTypeID = pti.ProductTypeID,
                                            UserID = userID,
                                            RecordTime = dt
                                        };
                                        union.Insert(sui);
                                    }
                                    str = "关联成功";
                                    return true;
                                default:
                                    PackageProductInfo ppinfo = new PackageProductInfo(var_packagePrdouctSN, var_productSN_list[0], pti.ProductTypeID, userID, dt);
                                    dal.Insert(ppinfo);
                                    str = "关联成功";
                                    return true;
                            }
                        }
                    }
                }
            }
        }

        public bool IsvalidProductSNtoUnion(string var_productSN, out string str)
        {
            SNUnion su = new SNUnion();
            if (!string.IsNullOrEmpty(dal.GetPackageProductbyProductSN(var_productSN).ProductSN) || !string.IsNullOrEmpty(su.LoadEntity(var_productSN).ProductSN))
            {
                str = "腔体序列号" + var_productSN + "已存在，不能重复关联！";
                return false;
            }
            else if (!string.IsNullOrEmpty(dal.GetPackageProductbyPackageProductSN(var_productSN).ProductSN) || su.SNUnion_GetbyPackageProductSN(var_productSN).Count > 0)
            {
                str = "腔体序列号" + var_productSN + "已经作为成品序列号使用过，无法再使用！";
                return false;
            }
            str = "";
            return true;
        }

        public bool IsvalidPackageProductSNtoUnion(string var_packagePrdouctSN, out string str)
        {
            SNUnion su = new SNUnion();
            if (!string.IsNullOrEmpty(dal.GetPackageProductbyPackageProductSN(var_packagePrdouctSN).ProductSN) || su.SNUnion_GetbyPackageProductSN(var_packagePrdouctSN).Count > 0)
            {
                str = "成品序列号已存在，不能重复关联！";
                return false;
            }
            else if (!string.IsNullOrEmpty(dal.GetPackageProductbyProductSN(var_packagePrdouctSN).ProductSN) || !string.IsNullOrEmpty(su.LoadEntity(var_packagePrdouctSN).ProductSN))
            {
                str = "成品序列号已经作为腔体序列号使用过，无法再使用！";
                return false;
            }
            str = "";
            return true;
        }

        public bool IsvalidProductTypeIDtoUnion(string var_productTypeID, out string str)
        {
            ProductType pt = new ProductType();
            ProductTypeInfo pti = pt.LoadEntity(var_productTypeID);
            if (string.IsNullOrEmpty(pti.ProductTypeID))
            {
                str = "没有检索到此产品类型，请先登记此产品类型信息！";
                return false;
            }
            str = "";
            return true;
        }

        public bool IsvalidProductTypeNametoUnion(string var_productTypeName, out string str)
        {
            ProductType pt = new ProductType();
            ProductTypeInfo pti = pt.GetProductTypebyName(var_productTypeName);
            if (string.IsNullOrEmpty(pti.ProductTypeID))
            {
                str = "没有检索到此产品类型，请先登记此产品类型信息！";
                return false;
            }
            str = "";
            return true;
        }


        public int GetCountforPrint(string var_productSN)
        {
            int amount = 0;
            string productTypeID = dal.GetPackageProductbyPackageProductSN(var_productSN).ProductTypeID;
            ProductType pt = new ProductType();
            if (pt.LoadEntity(productTypeID).CustomerName == "诺西(NSN)")
            {
                amount = dal.GetCountforPrint(productTypeID);
            }
            return amount;
        }

        public string[] GetPackageProductSNsforPrint(string sN3BK, int amount)
        {
            return dal.GetPackageProductSNsforPrint(sN3BK, amount);
        }

        public bool SetPackageProductSNsPrinted(string sN3BK, int amount)
        {
            return dal.SetPackageProductSNsPrinted(sN3BK, amount);
        }

        public bool AutoUnionforPackageProductSN(PackageProductInfo ppi)
        {
            try
            {
                dal.AutoUnionforPackageProductSN(ppi);
            }
            catch
            {
                return false;
            }
            return true;
        }

        public bool AutoBatchUnionforPackageProductSNs(PackageProductInfo ppi, DataTable dt)
        {
            return dal.AutoBatchUnionforPackageProductSNs(ppi, dt);
        }

        //七大工序与有源工序管控相关
        public bool Package_HasValidSevenStep(string productSN, string productTypeID)
        {
            return dal.Package_HasValidSevenStep(productSN, productTypeID);
        }

        public bool Package_HasValidRFSourceStep(string productSN, string productTypeID)
        {
            return dal.Package_HasValidRFSourceStep(productSN, productTypeID);
        }

        public bool IsValid_NineStep_DataCheck(string productSN, out string message)
        {
            return dal.IsValid_NineStep_DataCheck(productSN, out message);
        }
    }
}
